package com.yang.crawler.event.schema;


import com.google.common.eventbus.Subscribe;
import com.yang.crawler.common.BusinessException;
import com.yang.crawler.common.ResultCode;
import com.yang.crawler.event.IEventHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Component
public class EventHandlerPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof IEventHandler)) {
            return bean;
        }
        if (!methodHasSubscribeAnno(bean)) {
            throw new BusinessException(ResultCode.SERVER_ERROR);
        }
        return bean;
    }

    private boolean methodHasSubscribeAnno(Object bean) {
        for (Method method : bean.getClass().getDeclaredMethods()) {
            if (methodHasAnnotation(method, Subscribe.class)) {
                return true;
            }
        }
        return false;
    }

    private boolean methodHasAnnotation(Method method, Class<? extends Annotation> annotationClazz) {
        return method.isAnnotationPresent(annotationClazz);
    }
}